package com.cg.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.cg.config.PropertiesConfig;
import com.google.gson.Gson;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SmsServiceAlibabaImpl
 * @Description TODO
 * @Author CG
 * @Date 2023/12/31 10:19
 **/
public class SmsServiceAlibabaImpl implements SmsService {

    @Resource
    private PropertiesConfig propertiesConfig;

    @Override
    public String sendCode(String phone, String code) {
        // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
        DefaultProfile profile = DefaultProfile.getProfile(propertiesConfig.getRegionId(),
                propertiesConfig.getAccessKeyId(),
                propertiesConfig.getAccessKeySecret());

        String responseCode = "";
        IAcsClient client = new DefaultAcsClient(profile);


        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(propertiesConfig.getSignName());
        request.setTemplateCode(propertiesConfig.getTemplateCode());
        request.setPhoneNumbers(phone);
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        Gson gson = new Gson();
        request.setTemplateParam(gson.toJson(map));
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            responseCode = gson.toJson(response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseCode;
    }
}
